package com.fruit.service.sms.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.mapper.sms.SmsCodeMapper;
import com.fruit.pojo.sms.SmsCodeValidate;
import com.fruit.pojo.sms.SmsTemplet;
import com.fruit.service.sms.SmsCodeManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import com.fruit.util.sms.code.NeteaseSms;


@Service("smsCodeService")
public class SmsCodeService implements SmsCodeManager{
	

	@Autowired
	private SmsCodeMapper smsCodeMapper;

	@Override
	public String sendSmsCode(String type,String code, String phone) {
		SmsTemplet st = smsCodeMapper.getSmsTempletByCode(type);
		String result = null;
		if(st != null){
			st.setUrl(st.getSendUrl());
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			//模板id			
			nvps.add(new BasicNameValuePair("templateid", st.getTempletId()));
			//参数jsonArray形式
			nvps.add(new BasicNameValuePair("mobiles","['"+phone+"']"));
			nvps.add(new BasicNameValuePair("params", "['"+code+"']"));
			
			result = NeteaseSms.newPost(st, nvps);
		}
		
		return result;
	}
	
	
	@Override
	public String sendSmsNotice(String type, String phones, String params) {
		SmsTemplet st = smsCodeMapper.getSmsTempletByCode(type);
		String result = null;
		if(st != null){
			st.setUrl(st.getSendUrl());
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			//模板id			
			nvps.add(new BasicNameValuePair("templateid", st.getTempletId()));
			//参数jsonArray形式
			nvps.add(new BasicNameValuePair("mobiles",phones));
			nvps.add(new BasicNameValuePair("params", params));
			
			result = NeteaseSms.newPost(st, nvps);
		}
		
		return result;
	}

	@Override
	public int saveSmsCode(SmsCodeValidate code){
		return smsCodeMapper.saveSmsCode(code);
	}

	@Override
	public int updateSmsCode(SmsCodeValidate code){
		 return smsCodeMapper.updateSmsCode(code);
	}

	@Override
	public SmsCodeValidate getSmsCode(SmsCodeValidate code){
		return smsCodeMapper.getSmsCode(code);
	}

	@Override
	public SmsCodeValidate getSmsData(SmsCodeValidate code){
		return smsCodeMapper.getSmsData(code);
	}

	@Override
	public SmsCodeValidate getSmsTime(SmsCodeValidate sv){
		return smsCodeMapper.getSmsTime(sv);
	}


	@Override
	public void intiSmsData(SmsCodeValidate sv){
		smsCodeMapper.intiSmsData(sv);
	}

	@Override
	public SmsCodeValidate getSmsIsExpire(SmsCodeValidate code){
		return smsCodeMapper.getSmsIsExpire(code);
	}

	@Override
	public void upudateIsSue(SmsCodeValidate code) {
		smsCodeMapper.upudateIsSue(code);
	}

	public void updateIsuser(SmsCodeValidate sv){
		smsCodeMapper.updateIsuser(sv);
	}

	@Override
	public Map<String, Object> sendSmsCode(SmsCodeValidate sms) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		String msg ="",code="";
		try{
		SmsCodeValidate validate = smsCodeMapper.getSmsData(sms);
		if(validate == null){
			sms.setExpireTime("600");
			sms.setCode(CustomUtil.buildRandom(6) + "");
			sms.setSendNum(0);
			msg = sendDB(sms, true);
			
			return resMap;
		}
		Date createTime = DateUtil.fomatDateTime(validate.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
		
		int days = DateUtil.daysOfTwo(createTime,new Date());
		if(days != 0){
			validate.setSendNum(0);
			smsCodeMapper.intiSmsData(validate);
			sms.setExpireTime("600");
			sms.setCode(CustomUtil.buildRandom(6) + "");
			msg = sendDB(sms, false);
			return resMap;
		}
		if(validate.getSendNum() > 10){
			msg = "max";
			return resMap;
		}
		if(validate.getSendNum() < 3){
			sms.setExpireTime("600");
			code =CustomUtil.buildRandom(6)+"";
			sms.setCode(code);
			msg = sendDB(sms, false);
			return resMap;
		}
		long  now = System.currentTimeMillis();
		long  dates = Long.valueOf(DateUtil.dateToStamp(validate.getCreateTime())).longValue();
		if(validate.getSendNum() >=3 && ((now/1000) - (dates/1000)) > 900){
			sms.setExpireTime("600");
			code =CustomUtil.buildRandom(6)+"";
			sms.setCode(code);
			msg = sendDB(sms, false);
			return resMap;
		}
		msg = "often";
		return resMap;
		}catch(Exception e){
			msg = "exception";
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return resMap;
		}finally{
			if(StringUtils.equals(msg, "success")){
				resMap.put("code", sms.getCode());
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, msg, "发送成功"));
				
			}else if(StringUtils.equals(msg, "max")){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, msg, "获取验证码已经达到上线请在次日后再试"));
			}else if(StringUtils.equals(msg, "exception")){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, msg, "系统异常"));
			}else if(StringUtils.equals(msg, "often")){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, msg, "请求次数过于频繁请稍后再试"));
			}else{
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, msg, "发送失败"));
			}
		}
	}
	
	
	
	private String sendDB(final SmsCodeValidate sms, Boolean o) {
		try {
			int i = 0;
			if (o) {
				sms.setIsUse("00");
				i = smsCodeMapper.saveSmsCode(sms);
			} else {
				sms.setIsUse("00");
				i = smsCodeMapper.updateSmsCode(sms);
			}
			if (i >= 1) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						sendSmsCode("register", sms.getCode(),sms.getPhone());
					}
				}).start();
			}
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}

	@Override
	public String getValidateCode(String phone, String code, String type) {
		String msg = "ok";
		try{
		SmsCodeValidate sms = new SmsCodeValidate();
		sms.setPhone(phone);
		sms.setCode(code);
		sms.setTypes(type);
		SmsCodeValidate validate = smsCodeMapper.getSmsCode(sms);
		if(validate == null){
			msg = "not_exists";
		}else{
			if ("01".equals(validate.getIsUse())) {
				msg ="expire";
			}else{
				String time = validate.getExpireTime();
				long lose = Long.parseLong(time);

				Long newTime = System.currentTimeMillis();
				if (lose < (newTime / 1000)) {
					msg ="expire";
				}
			}
		}
		}catch(Exception e){
			msg = "error";
		}
		return msg;
	}

	
	
}
